<?php
/**
 * 内容管理
 */

namespace backend\controllers;

use common\models\Attributes;
use common\models\Catalog;
use common\models\Meta;
use common\models\Post;
use common\models\PostAttr;
use yii;
use common\models\Article;

class PostController extends CommonController
{
    public function actions()
    {
        return [
            'Kupload' => [
                'class' => 'pjkui\kindeditor\KindEditorAction'
            ]
        ];
    }

    public function actionIndex()
    {
        if ($this->get('act') && Yii::$app->request->isAjax) {
            switch ($this->get('act')) {
                case 'getArticle':
                    return $this->getArticle();
                    break;
                case 'getArticleInfo':
                    return $this->getArticleInfo();
                    break;
                case 'getAttr':
                    return $this->getAttr();
                    break;
                default:
                    break;
            }
        } else {
            $query = Post::find()->orderBy(['recommend' => SORT_DESC, 'sort' => SORT_ASC, 'id' => SORT_DESC]);
            $title = Yii::$app->request->get('title');
            $catalog_id = Yii::$app->request->get('catalog_id');
            $title && $query->andWhere(['like', 'title', $title]);
            if ($catalog_id) {
                $catalog = new Catalog();
                $childIdes = $catalog->getChildIdes($catalog_id);
                if ($childIdes) {
                    $ids = $catalog_id . ',' . $childIdes;
                    $query->andWhere("catalog_id in(:ids)", [':ids' => $ids]);
                } else {
                    $query->andWhere('catalog_id=:catalog_id', [':catalog_id' => $catalog_id]);
                }
            }
            $this->setQuery($query);
            return $this->query();
        }
    }

    public function actionCreate()
    {
        $model = new Post();
        $model->sort = 255;
        $this->setModel($model);
        $meta = new Meta();
        $this->setParams(['meta' => $meta, 'p1' => [], 'p2' => []]);
        return $this->save();
    }

    public function actionUpdate($id)
    {
        $model = Post::findOne($id);
        $meta = Meta::get($model->tableName(), $model->id);
        $p1 = $p2 = [];
        if ($model->photos) {
            $photos = explode('|', $model->photos);
            foreach ($photos as $photo) {
                $p1[] = Yii::getAlias('@frontendUrl') . $photo;
                $p2[] = ['url' => yii\helpers\Url::to(['upload-photos']), 'key' => $photo];
            }
        }
        $this->setParams(['meta' => $meta, 'p1' => $p1, 'p2' => $p2]);
        $this->setModel($model);
        return $this->save();
    }

    public function actionDelete()
    {
        $this->setModel(new Post());
        $this->delete();
    }

    /**
     * @param \common\models\Post $model
     */
    protected function savedHandle($model)
    {
        if ($this->post('post-article_id')) {
            Article::saveFromPost($model);
        }
        Meta::log($model->tableName(), $model->id);
        PostAttr::saveFromPost($model->id);
    }

    private function getArticle()
    {
        $key = $this->get('key');
        $query = Article::find()->orderBy(['id' => SORT_DESC]);
        if ($key) {
            $query->andWhere(['like', 'title', $key]);
        }
        $dataProvider = new yii\data\ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 15,
            ]
        ]);
        return $this->renderAjax('/catalog/get-article', ['dataProvider' => $dataProvider]);
    }

    private function getArticleInfo()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $id = $this->get('id');
        $article = Article::findOne($id);
        if ($article) {
            return array_merge(['code' => '1'], $article->attributes);
        } else {
            return ['code' => '0'];
        }
    }

    private function getAttr()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $id = $this->get('catalog_id');
        //需要一级父类id
        $firstParent = Catalog::getFirstParent($id);

        $attributes = Attributes::find()->select("id,name")->where("catalog_id=" . $firstParent->id)->orderBy("id asc")->asArray()->all();

        //查看是否已经有属性值
        $post_id = $this->get('post_id');
        if ($post_id) {
            $postVal = PostAttr::getPostAttr($post_id);
            foreach ($attributes as $key => $item) {
                $attributes[$key]['val'] = "";
                foreach ($postVal as $k => $v) {
                    if ($item['id'] == $v['attr_id']) {
                        $attributes[$key]['val'] = $v['val'];
                        break;
                    }
                }
            }
        } else {
            foreach ($attributes as $key => $item) {
                $attributes[$key]['val'] = "";
            }
        }
        return $attributes;
    }

}